package com.longge;

import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-05-02 02:21
 */
public class SortString {

    public String sortString(String s) {
        char[] chars = s.toCharArray();
        TreeMap<Character, Integer> map = new TreeMap<>();
        for (char aChar : chars) {
            map.merge(aChar, 1, (a, b) -> a + b);
        }
        StringBuilder sb = new StringBuilder();
        Boolean sign = true;
        while (!map.isEmpty()) {
            TreeSet<Character> characters = new TreeSet<>(map.keySet());
            if (sign) {
                while (!characters.isEmpty()) {
                    Character c = characters.pollFirst();
                    sb.append(c);
                    if (map.get(c) == 1) {
                        map.remove(c);
                    } else {
                        map.put(c, map.get(c) - 1);
                    }
                }
                sign = false;
            } else {
                while (!characters.isEmpty()) {
                    Character c = characters.pollLast();
                    sb.append(c);
                    if (map.get(c) == 1) {
                        map.remove(c);
                    } else {
                        map.put(c, map.get(c) - 1);
                    }
                }
                sign = true;
            }

        }
        return sb.toString();
    }
}
